using System;
using UnityEngine;

//火箭
public class Projectile : MonoBehaviour
{
    public static Action<Enemy, float> OnEnemyHit;//敌人受伤委托

    [SerializeField, Header("子弹移动速度")]
    protected float moveSpeed = 10f;
    protected Enemy _enemyTarget; // 目标敌人

    [NonSerialized]
    public float damage = 2f;
    [SerializeField, Header("造成伤害的距离")]
    private float minDistanceToDealDamage = 0.1f;

    public TurretProjectile Turretowner { get; set; }

    protected virtual void Update()
    {
        if (_enemyTarget != null)
        {
            MoveProjectile();
            RotateProjectile();
        }
    }

    protected virtual void MoveProjectile()
    {
        // 将子弹向目标位置移动
        transform.position = Vector2.MoveTowards(transform.position, _enemyTarget.transform.position, moveSpeed * Time.deltaTime);

        // 计算子弹与目标的距离
        float distanceToTarget = (_enemyTarget.transform.position - transform.position).magnitude;
        // 如果子弹与目标的距离小于最小距离，造成伤害并回收子弹
        if (distanceToTarget < minDistanceToDealDamage)
        {
            _enemyTarget._enemyHealth.DealDamage(damage);
            OnEnemyHit?.Invoke(_enemyTarget, damage);
            Turretowner.ResetTurretProjectile(); //重置装载的子弹
            ObjectPooler.ReturnToPool(gameObject);
        }
    }

    //控制子弹自动旋转
    private void RotateProjectile()
    {
        Vector3 enemyPos = _enemyTarget.transform.position - transform.position; // 计算目标敌人相对于子弹的位置向量
        float angle = Vector3.SignedAngle(transform.up, enemyPos, transform.forward); // 计算旋转角度

        transform.Rotate(0f, 0f, angle); // 绕Z轴旋转子弹
    }

    public void SetEnemy(Enemy enemy)
    {
        // 设置目标敌人
        _enemyTarget = enemy;
    }

    //重置炮弹
    public void ResetProjectile()
    {
        _enemyTarget = null;
        transform.localRotation = Quaternion.identity;
    }
}
